package com.sam.im.heiqun.uis.activities;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.VedioEntity;
import com.yuyh.library.utils.ScreenUtil;

import org.greenrobot.eventbus.EventBus;

import mabeijianxi.camera.MediaRecorderActivity;
import mabeijianxi.camera.model.AutoVBRMode;
import mabeijianxi.camera.model.MediaRecorderConfig;
import mabeijianxi.camera.util.DeviceUtils;
import com.sam.im.heiqun.utils.StringUtils;
import mabeijianxi.camera.views.SurfaceVideoView;

public class VideoPlayerActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, SurfaceVideoView.OnPlayStateListener, MediaPlayer.OnErrorListener, View.OnClickListener, MediaPlayer.OnInfoListener, MediaPlayer.OnCompletionListener {

    /**
     * 播放控件
     */
    private SurfaceVideoView mVideoView;
    /**
     * 暂停按钮
     */
    private View mPlayerStatus;
    private View mLoading;
    private ImageView imgState ;
    private ImageButton btCancle ;
    private ImageButton btSure ;
    /**
     * 播放路径
     */
    private String mPath;
    /**
     * 是否需要回复播放
     */
    private boolean mNeedResume;
    private String videoScreenshot;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 防止锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
       // mPath = getIntent().getStringExtra("path");
        Intent intent = getIntent();
        mPath = intent.getStringExtra(MediaRecorderActivity.VIDEO_URI);//视屏地址
        videoScreenshot = intent.getStringExtra(MediaRecorderActivity.VIDEO_SCREENSHOT);//缩略图
        String vediourl = intent.getStringExtra("vediourl");
        if (StringUtils.isEmpty(mPath)&&StringUtils.isEmpty(vediourl)) {
            finish();
            return;
        }
        setContentView(R.layout.activity_video_player);
        mVideoView = (SurfaceVideoView) findViewById(R.id.videoview);
        int screenWidth = getScreenWidth(VideoPlayerActivity.this);
        //int videoHight = (int) (screenWidth / (MediaRecorderBase.SMALL_VIDEO_WIDTH / (MediaRecorderBase.SMALL_VIDEO_HEIGHT * 1.0f)));
        int videoHight = ScreenUtil.getScreenHeight(VideoPlayerActivity.this)*1/2;
        mVideoView.getLayoutParams().height = videoHight;
        mVideoView.requestLayout();
        mPlayerStatus = findViewById(R.id.play_status);
        mLoading = findViewById(R.id.loading);
        btCancle = (ImageButton) findViewById(R.id.cancle_bt);
        btSure = (ImageButton) findViewById(R.id.sure_bt);
        imgState = (ImageView) findViewById(R.id.play_status);
        btCancle.setOnClickListener(this);
        btSure.setOnClickListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnPlayStateListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnClickListener(this);
        mVideoView.setOnInfoListener(this);
        mVideoView.setOnCompletionListener(this);

        findViewById(R.id.root).setOnClickListener(this);
        if (vediourl != null&&!"".equals(vediourl)) {
            mVideoView.setVideoPath(vediourl);
            btSure.setVisibility(View.GONE);
            btCancle.setEnabled(false);
            btSure.setEnabled(false);
            btCancle.setVisibility(View.GONE);
        }else{
            mVideoView.setVideoPath(mPath);
            btSure.setVisibility(View.VISIBLE);
            btCancle.setEnabled(true);
            btSure.setEnabled(true);
            btCancle.setVisibility(View.VISIBLE);
        }

    }

    public int getScreenWidth(Activity context) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        int W = mDisplayMetrics.widthPixels;
        return W;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null && mNeedResume) {
            mNeedResume = false;
            if (mVideoView.isRelease())
                mVideoView.reOpen();
            else
                mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mNeedResume = true;
                mVideoView.pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mVideoView != null) {
            mVideoView.release();
            mVideoView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoView.setVolume(SurfaceVideoView.getSystemVolumn(this));
        mVideoView.start();
        mLoading.setVisibility(View.GONE);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()) {// 跟随系统音量走
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
                mVideoView.dispatchKeyEvent(this, event);
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onStateChanged(boolean isPlaying) {
        mPlayerStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
    }
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (!isFinishing()) {
            // 播放失败
        }
        finish();
        return false;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.videoview:
            case R.id.root:
                if (mVideoView.isPlaying()){
                    mVideoView.pause();
                }else {
                    mVideoView.start();
                }
                //finish();
                break;
            case R.id.cancle_bt://放弃视屏 重新回到视频界面
                MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                        .doH264Compress(new AutoVBRMode()
//                        .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
                        )
                        .setMediaBitrateConfig(new AutoVBRMode()
//                        .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
                        )
                        .smallVideoWidth(480)
                        .smallVideoHeight(600)
                        .recordTimeMax(8 * 1000)
                        .maxFrameRate(70)
                        .captureThumbnailsTime(1)
                        .recordTimeMin((int) (1.5 * 1000))
                        .build();
                MediaRecorderActivity.goSmallVideoRecorder(VideoPlayerActivity.this,VideoPlayerActivity.class.getName(), config);
                finish();
                break;
            case R.id.sure_bt://确定发送视屏
                int duration = mVideoView.getDuration();
                Log.i("info","视屏的path=="+mPath+"  缩略图=="+videoScreenshot);
                VedioEntity vedioEntity = new VedioEntity();
                vedioEntity.setVedioPath(mPath);
                vedioEntity.setVedioSize(duration);
                vedioEntity.setVedioBitmappath(videoScreenshot);
                EventBus.getDefault().post(vedioEntity);
                finish();
                break;
        }
    }
    @Override
    public void onCompletion(MediaPlayer mp) {
        if (!isFinishing())
            mVideoView.reOpen();
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                // 音频和视频数据不正确
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (!isFinishing())
                    mVideoView.pause();
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                if (!isFinishing())
                    mVideoView.start();
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                if (DeviceUtils.hasJellyBean()) {
                    mVideoView.setBackground(null);
                } else {
                    mVideoView.setBackgroundDrawable(null);
                }
                break;
        }
        return false;
    }
}
